/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.www.cnblogs.com.erbing;

public class InterruptDemo {

    /**
     * 输出：调用 interrupt() 时，只是设置了线程中断标识，线程依旧会继续执行当前方法，执行完之后再退出线程。
     * do something...
     * continue do something...
     * do something...
     * continue do something...
     * do something...
     * 线程被中断...
     * continue do something...
     */
    public static void main(String[] args) throws InterruptedException {
        Proxy proxy = new Proxy();
        proxy.start();

        Thread.sleep(6000);
        proxy.stop();
    }

    static class Proxy {
        // 自定义线程终止标志位
        private volatile boolean terminated = false;

        private boolean started = false;

        Thread t;

        public synchronized void start() {
            if (started) {
                return;
            }
            started = true;
            terminated = false;

            t = new Thread(() -> {
                while (!terminated) { // 取代 while (true)
                    System.out.println("do something...");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // 如果其它线程中断此线程，抛出异常时，需重新设置线程中断状态，因为 JVM 的异常处理会清除线程的中断状态。
                        System.out.println("线程被中断...");
                        Thread.currentThread().interrupt();
                    }
                    System.out.println("continue do something...");
                }
                started = false;
            });
            t.start();
        }

        public synchronized void stop() {
            // 设置中断标志
            terminated = true;
            t.interrupt();
        }
    }

}